package com.cet.algorithm.二叉树.二叉树的遍历;

import java.util.*;

/**
 * @program: algorithm
 * @description: 二叉树后序遍历
 * @author: 陈恩涛
 * @create: 2022-07-14 11:09
 **/
public class LC145 {

    public static void main(String[] args) {

    }

    public List<Integer> postorderTraversal(TreeNode root) {
        final List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        final Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            final TreeNode node = stack.pop();
            result.add(node.val);
            // 中右左遍历顺序
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        // 翻转后，左右中
        Collections.reverse(result);
        return result;
    }
    /**
     * 节点标记法
     * @param root 根节点
     * @return 结果
     */
    public static List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root != null) {
            stack.push(root);
        }
        TreeNode cur = null;
        while (!stack.isEmpty()) {
            cur = stack.peek();
            if (cur != null) {
                stack.pop();
                stack.push(cur);
                stack.push(null);
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.left != null) {
                    stack.push(cur.left);
                }
            } else {
                // null 出栈
                stack.pop();
                // 节点二次访问，出栈处理
                cur = stack.pop();
                result.add(cur.val);
            }
        }
        return result;
    }

}
